<template>
  <!-- 班次设置 -->
  <div class="shift-manage route-page">
    <a-card class="route-content" body-style="padding: 12px" title="班次设置">
      <a-table
        :dataSource="dataList"
        :columns="columns"
        rowKey="id"
        :pagination="pagination"
        @change="handleTableChange"
      >
        <template #title>
          <a-row type="flex" justify="space-between">
            <a-col>
              <a-input-search
                v-model:value="shift_name"
                placeholder="搜索班次名称"
                :allowClear="true"
                @search="getDataList(true)"
              />
            </a-col>
            <a-col>
              <a-button type="primary" @click="addShift()">
                <template #icon>
                  <PlusOutlined />
                </template>
                新建班次
              </a-button>
            </a-col>
          </a-row>
        </template>
        <template #bodyCell="{ text, record, index, column }">
          <template v-if="column.key === 'time_detail'">
            <a-space direction="vertical">
              <div v-for="(item, index) of text" :key="index">
                <span v-if="item.startNextDay">次日</span>
                <span>{{ item.start }}</span>
                ~
                <span v-if="item.endNextDay">次日</span>
                <span>{{ item.end }}</span>
              </div>
            </a-space>
          </template>
          <template v-if="column.key === 'action'">
            <a-button type="link" @click="addShift(text, true)">
              查看
            </a-button>
            <a-button type="link" @click="addShift(text)"> 编辑 </a-button>
            <a-button type="link" danger @click="removeShift(record)">
              删除
            </a-button>
          </template>
        </template>
      </a-table>
    </a-card>
    <add-shift
      :visible="addVisible"
      :id="editId"
      :isCheck="isCheck"
      @cancel="addVisible = false"
      @success="addShiftSuccess"
    />
  </div>
</template>

<script>
import { defineComponent, reactive, toRefs, computed } from "vue";
import { PlusOutlined } from "@ant-design/icons-vue";
import AddShift from "./modules/AddShift.vue";
import request from "../../../common/utils/request";
import utils from "../../../common/utils/utils";
import { message } from "ant-design-vue";

export default defineComponent({
  name: "companyShift",
  components: { PlusOutlined, AddShift },
  setup() {
    const state = reactive({
      dataList: [],
      addVisible: false,
      page: 1,
      pageSize: 20,
      total: 0,
      shift_name: "",
      time_sort: "desc", // asc 正序，desc倒序
      editId: 0,
      isCheck: false,
    });

    const addShift = (id, isCheck = false) => {
      if (id && !isCheck) {
        // 编辑
        request
          .get("/org", "/shift/group/check", {
            shift_id: id,
          })
          .then((res) => {
            if (res.group_arr.length) {
              const groupStr = res.group_arr.join("、");
              utils.modalConfirm({
                content: `有【${groupStr}】等 ${res.group_arr.length} 个排班组正在使用该班次。班次修改后，将影响到这些排班组的排班，你确定要修改吗？`,
                onOk: () => {
                  state.editId = id;
                  state.isCheck = false;
                  state.addVisible = true;
                },
              });
            } else {
              state.editId = id;
              state.isCheck = false;
              state.addVisible = true;
            }
          });

        return;
      }
      state.editId = id || 0;
      state.isCheck = isCheck;
      state.addVisible = true;
    };
    const addShiftSuccess = () => {
      state.addVisible = false;
      getDataList(true);
    };
    const removeShift = (record) => {
      utils.modalConfirm({
        content: `确认删除班次“${record.shift_name}”吗？`,
        okType: "danger",
        onOk: () => {
          request
            .del("/org", "/shift", {
              id: record.id,
              needMsg: true,
            })
            .then((res) => {
              message.success(res.msg || "删除成功！");
              getDataList();
            });
        },
      });
    };

    const pagination = computed(() => ({
      total: state.total,
      current: state.page,
      pageSize: state.pageSize,
      showTotal: (total) => `共${total}条`,
      showSizeChanger: true,
    }));
    const handleTableChange = (pager, filter, sorter) => {
      state.page = pager.current;
      state.pageSize = pager.pageSize;
      state.time_sort = sorter.order == "descend" ? "desc" : "asc";
      getDataList();
    };

    const getDataList = (init = false) => {
      if (init) {
        state.page = 1;
      }
      const params = {
        page: state.page,
        pageSize: state.pageSize,
        time_sort: state.time_sort,
      };
      if (state.shift_name) {
        params.shift_name = state.shift_name;
      }
      request.get("/org", "/shift/list", params).then((res) => {
        state.dataList = res.list.map((item) => ({
          ...item,
          time_detail: utils.getShiftTimeDetail(item.time_detail),
        }));
        state.total = res.total;
      });
    };

    const init = () => {
      getDataList(true);
    };
    init();
    return {
      columns,
      pagination,
      ...toRefs(state),
      addShift,
      addShiftSuccess,
      getDataList,
      handleTableChange,
      removeShift,
    };
  },
});

const columns = [
  {
    title: "班次名称",
    dataIndex: "shift_name",
    key: "shift_name",
  },
  {
    title: "考勤时间",
    dataIndex: "time_detail",
    key: "time_detail",
  },
  {
    title: "创建人",
    dataIndex: "create_name",
    key: "create_name",
  },
  {
    title: "最后更新时间",
    dataIndex: "updated_at",
    key: "updated_at",
    sorter: true,
    defaultSortOrder: "descend",
    sortDirections: ["descend", "ascend"],
  },
  {
    title: "操作",
    dataIndex: "id",
    key: "action",
  },
];
</script>
<style lang="less" scoped>
.shift-manage {
  :deep(.ant-table-title) {
    padding: 8px 0;
  }
  :deep(.ant-card-head-title) {
    padding: 15px 0;
  }
}
</style>
